package com.aaa.tmr.controller;

import com.aaa.tmr.entity.User;
import com.aaa.tmr.service.CommonFileService;
import com.aaa.tmr.service.UserService;
import com.aaa.tmr.util.BussinessConstants;
import com.aaa.tmr.util.Result;
import com.aaa.tmr.util.ReturnStatus;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 用户信息表(User)表控制层
 *
 * @author makejava
 * @since 2021-03-18 19:16:21
 */
@Controller
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    @Resource
    private HttpSession session;

    @Resource
    private CommonFileService commonFileService;

    /**
     * 跳转登录
     */
    @RequestMapping("toLogin")
    public String toLogin(Model model){
        model.addAttribute("errorInfo",session.getAttribute("errorInfo"));
        System.out.println("用户名或者密码错误"+session.getAttribute("errorInfo"));
        return "back/login";
    }

    /**
     * 登录方法
     */
    @RequestMapping("login")
    public String login(User user){
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUserName(), user.getPassword());
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(usernamePasswordToken);
            Session session = currentUser.getSession();
            session.setAttribute("userInfo",currentUser.getPrincipal());
            this.session.removeAttribute("errorInfo");
            return "redirect:/back/toIndex";
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        session.setAttribute("errorInfo","用户名或密码错误");
        return "redirect:toLogin";
    }

    /**
     * 跳转分页列表页面
     * @return 列表页面
     */
    @RequestMapping("toUser")
    public String toUser(){
        return "back/user-page";
    }
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public User selectOne(Integer id) {
        return this.userService.queryById(id);
    }


    /**
     * 分页查询方法
     *
     * @param page
     * @param limit
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping("queryAll")
    public Result<java.util.List> queryAll(Integer page, Integer limit, User user) {
        PageInfo pageInfo = userService.queryAll(page, limit, user);
        return new Result<>(ReturnStatus.SUCCESS.getCode(), ReturnStatus.SUCCESS.getMessage(),
                pageInfo.getTotal(), pageInfo.getList());
    }


    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @RequestMapping("insert")
    @ResponseBody
    public Result<User> insert(User user,String role) {
        //根据登录名查询用户(用户名不能重复)
        User userTemp = userService.queryByLoginName(user.getLoginName());
        //如果用户不为空，返回错误
        String password=user.getPassword();
        String[] sha512 = BussinessConstants.getSha512(password);
        user.setPassword(sha512[0]);
        user.setSalt(sha512[1]);
        User insert = userService.insert(user);
        String[] roles = role.split(",");
        if (insert!=null){
            userService.insertUserRole(insert.getUserId(), roles);
            return new Result<>(ReturnStatus.SUCCESS.getCode(),
                    ReturnStatus.SUCCESS.getMessage(), 0L,
                   insert );
        }
        return null;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @PutMapping("update")
    @ResponseBody
    public Result<User> update(User user) {
        return new Result<>(ReturnStatus.SUCCESS.getCode(),
                ReturnStatus.SUCCESS.getMessage(), 0L,
                this.userService.update(user));
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */

    @DeleteMapping("deleteById")
    @ResponseBody
    public Result<Boolean> deleteById(Integer userId) {
        return new Result<>(ReturnStatus.SUCCESS.getCode(),
                ReturnStatus.SUCCESS.getMessage(), 0L,
                this.userService.deleteById(userId));
    }

   /**
     * description: 用户类型删除方法
     * @param userIds userIds
     * @return Result<Integer>
     * @author Marko
     * @Date 2021/3/21 18:14
     */
    @DeleteMapping("deleteByIds")
    @ResponseBody
    public Result<Integer> deleteByIds(String userIds){
        return new Result<>(ReturnStatus.SUCCESS.getCode(),ReturnStatus.SUCCESS.getMessage()
                ,0L,userService.deleteByIds(userIds));
    }

    /**
     * 头像上传
     * @param headPic
     * @return
     */
    @ResponseBody
    @RequestMapping("uploadHeadPic")
    public Result<java.util.Map> uploadHeadPic(@RequestParam MultipartFile headPic){
        return new Result<>(ReturnStatus.SUCCESS.getCode(),
                ReturnStatus.SUCCESS.getMessage(), 0L,
                this.commonFileService.uploadFile(headPic,"files/user/images"));
    }
    /**
     * 查询所有部门
     * @return
     */
    @ResponseBody
    @GetMapping("findAllDept")
    public List<Map<String, Object>> findAllDept() {
        List<Map<String, Object>> allDept = userService.findAllDept();
        return allDept;
    }

    /**
     * 查询所有角色
     * @return
     */
    @ResponseBody
    @GetMapping("findAllRole")
    public List<Map<String, Object>> findAllRole() {
        List<Map<String, Object>> allRole = userService.findAllRole();
        return allRole;
    }

    /**
     * @param user:
     * @return com.cloudwise.trademark.entity.ReturnBean
     * @create by: IvanZ
     * @description : 修改密码
     * @create time: 2020/12/18 18:42
     */
    @ResponseBody
    @PutMapping("updatePassword")
    public Result updatePassword(User user) {

        //加密之前的密码
        String password = user.getPassword();

        String[] sha512 = BussinessConstants.getSha512(password);
        System.out.println(sha512.toString());
        user.setPassword(sha512[0]);
        user.setSalt(sha512[1]);
        //生成密文传入数据库=
        User update = userService.update(user);
        if (update != null) {
            return new Result(ReturnStatus.SUCCESS.getCode(), ReturnStatus.SUCCESS.getMessage(),
                    0L,update);
        }
        return new Result(ReturnStatus.FAIL.getCode(), ReturnStatus.FAIL.getMessage(),
                0L,null);
    }
}
